<template>
    <div class="app-container">
        <div class="searchs-content">
            <el-button
                v-permission="['om:equip:ad:file:add']"
                type="primary"
                size="mini"
                plain
                icon="el-icon-plus"
                @click="addDialog"
                >新增</el-button
            >
            <el-form
                class="searchForm"
                :inline="true"
                size="mini"
                ref="searchForm"
                :model="searchForm"
                label-width="80px"
            >
                <el-form-item>
                    <el-button
                        type="primary"
                        size="mini"
                        icon="el-icon-search"
                        @click="doSearch"
                        >搜索</el-button
                    >
                </el-form-item>
            </el-form>
        </div>

        <Table
            :tableHeader="tableHeader"
            :tableData="tableData"
            :tableLoading="listLoading"
        >
            <template slot="action" slot-scope="scope">
                <el-button
                    type="primary"
                    size="mini"
                    @click="addDialog(scope.row)"
                    v-permission="['om:equip:ad:file:edit']"
                    >编辑</el-button
                >
                <el-button
                    type="danger"
                    size="mini"
                    @click="handleDelete(scope.row)"
                    v-permission="['om:equip:ad:file:remove']"
                    >删除</el-button
                >
            </template>
        </Table>
        <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="fetchData"
        />

        <!-- 弹框 -->
        <Dialog
            :visible="visible"
            width="32%"
            :loading="dialogBtnLoading"
            :title="dialogTitle"
            @confirmDialog="confirmDialog"
            @cancelDialog="cancelDialog"
        >
            <el-form
                ref="dialogForm"
                :model="dialogForm"
                label-width="110px"
                :rules="dialogRules"
                size="small"
            >
                <el-form-item label="广告名称" prop="fileName">
                    <el-input
                        class="ipt"
                        v-model="dialogForm.fileName"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="设备分类">
                    <el-select
                        class="ipt"
                        v-model="dialogForm.equipClassify"
                        placeholder="请选择设备分类"
                        disabled
                    >
                        <el-option
                            v-for="item in enums.EQUIP_CLASSIFY"
                            :key="item.code"
                            :label="item.label"
                            :value="item.code"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="广告图片(选择图片)" prop="fileAddr">
                    <el-upload
                        class="avatar-uploader"
                        action="#"
                        accept=".jpg,.jpeg,.png"
                        :http-request="uploadRequest"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        v-loading.fullscreen.lock="uploading"
                        element-loading-text="拼命上传中"
                        element-loading-spinner="el-icon-loading"
                        element-loading-background="rgba(0,0,0,0.1)"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <el-link type="primary" :href="imageUrl"  v-if="imageUrl" target="_blank">{{imageUrl}}</el-link>
                </el-form-item>
            </el-form>
        </Dialog>
    </div>
</template>

<script>
import { advertiseManage } from "@/api/manage";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";

import { mapGetters } from "vuex";
export default {
    components: { Pagination, Table, Dialog },
    data() {
        return {
            listLoading: true,
            total: 0,
            searchForm: {
                pageNum: 1,
                pageSize: 15,
            },

            tableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                {
                    label: "广告名称",
                    prop: "fileName",
                },
                {
                    label: "设备类型",
                    prop: "equipClassify",
                    formatter: (item) => {
                        let classify = this.enums.EQUIP_CLASSIFY.find((p) => {
                            return p.code == item.equipClassify;
                        });
                        return classify.label;
                    },
                },
                {
                    label: "创建人",
                    prop: "createBy",
                },
                {
                    label: "创建时间",
                    prop: "createTime",
                },
                { slot: "action", label: "操作", width: "300" },
            ],
            tableData: [],
            visible: false, //弹框标识
            dialogForm: {
                equipClassify: "",
                fileName: "",
                fileAddr: "",
            },
            dialogRules: {
                fileName: [
                    {
                        required: true,
                        message: "请输入广告名称",
                        trigger: "blur",
                    },
                ],
                fileAddr: [
                    {
                        required: true,
                        message: "请上传广告图片",
                        trigger: "change",
                    },
                ],
            },
            dialogTitle: "",

            dialogBtnLoading: false,

            factureOption: [], //运营商
            imageUrl: "",
            uploading: false,

            currentRow: {},
            IMGLink: this.IMGLink,
        };
    },
    computed: {
        ...mapGetters(["equipTypeCode", "enums"]),
    },

    async created() {
        // this.enumsJson = await this.$store.dispatch("enums/generateEnumMap");
        this.fetchData();
    },
    methods: {
        fetchData(val) {
            this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
            this.listLoading = true;
            this.tableData = [];
            this.total = 0;
            advertiseManage(
                "/list",
                "post",
                { ...removeNullUndefined(this.searchForm) },
                2
            )
                .then((res) => {
                    this.tableData = res.data;
                    this.total = +res.total;

                    this.searchForm.pageNum = +res.pageNum;
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },

        // 弹框取消
        cancelDialog() {
            this.visible = false;
            this.clearData();
            this.resetDialogForm("dialogForm");
        },
        clearData() {
            this.dialogForm = {
                equipClassify: this.equipTypeCode,
                fileName: "",
                fileAddr: "",
            };
            this.imageUrl = "";
        },
        // 弹框确认
        confirmDialog() {
            this.submitDialogForm("dialogForm");
        },
        // 新增
        async addDialog(row) {
            this.visible = true;

            if (row.id) {
                this.dialogTitle = "编辑";
                this.currentRow = { ...row };
                let { id, equipClassify, fileName, fileAddr } = row;
                this.dialogForm = {
                    id,
                    equipClassify,
                    fileName,
                    fileAddr,
                };
                this.imageUrl = this.IMGLink + fileAddr;
            } else {
                this.dialogTitle = "新增";
                this.currentRow = {};
                this.dialogForm = {
                    equipClassify: this.equipTypeCode,
                    fileName: "",
                    fileAddr: "",
                };
            }
        },
        handleDelete(row) {
            handleConfirm(
                "删除操作，会导致设备广告页不可用，确定继续？",
                "warning",
                "提示"
            )
                .then((res) => {
                    this.doDelete(row);
                })
                .catch((err) => {});
        },
        doDelete(row) {
            advertiseManage(`/delete/${row.id}`, "post").then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                    this.fetchData();
                }
            });
        },
        resetDialogForm(formName) {
            this.$refs[formName].resetFields();
        },
        submitDialogForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let msg = this.currentRow.id ? "编辑" : "新增";
                    handleConfirm(`确定要${msg}吗？`, "warning", "提示")
                        .then((res) => {
                            this.doAdd();
                        })
                        .catch((err) => {});
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },

        doSearch() {
            this.searchForm.pageNum = 1;
            this.fetchData();
        },

        doAdd() {
            this.dialogBtnLoading = true;
            let url = this.currentRow.id ? `/update` : "/insert";
            let params = { ...this.dialogForm };
            if (this.currentRow.id) {
                params.id = this.currentRow.id;
            }
            advertiseManage(url, "post", params, 1)
                .then((res) => {
                    if (res.code == 200) {
                        this.$message.success(res.message);
                        this.visible = false;
                        this.fetchData();
                    }
                })
                .finally(() => {
                    this.dialogBtnLoading = false;
                });
        },
        uploadRequest(file) {
            //自定义上传
            let formData = new FormData();
            formData.append("file", file.file);

            this.uploading = true;
            advertiseManage("/upload", "post", formData, 1)
                .then((res) => {
                    if (res.code == 200) {
                        let datas = res.data;
                        this.dialogForm.fileAddr = datas.fileUrl;

                        this.imageUrl = this.IMGLink + datas.fileUrl;
                    } else {
                        this.imageUrl = "";
                    }
                })
                .finally(() => {
                    this.uploading = false;
                })
                .catch(() => {
                    this.imageUrl = "";
                });
        },
        beforeAvatarUpload(file) {
            const isJPG =
                file.type === "image/jpeg" || "image/png" || "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error("只能是图片格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },
    },
};
</script>
<style lang="scss">
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style lang="scss" scoped>
@import "@/styles/common.scss";
.ipt {
    width: 96%;
}
.searchForm {
    .el-form-item {
        margin-bottom: 8px;
    }
}
::v-deep .el-input.is-disabled .el-input__inner {
    color: #333333;
}
.searchs-content {
    @include flexLayout(center, space-between);
}
</style>
